import json
import traceback

from pymysql import DatabaseError

from conf.config import MYSQL_CONFIG, logger
from db.mysql_db import MysqlClient
from utils.constants import TASK_STATUS


class TaskDAO(object):
    """ 任务访问对象 """
    def __init__(self, *args, **kwargs):
        super(TaskDAO, self).__init__(*args, **kwargs)

    @staticmethod
    def get_mysql_conn():
        """ 获取mysql连接 """
        mysql_conn = MysqlClient(MYSQL_CONFIG)
        return mysql_conn

    def get_task(self, task_id: int) -> dict:
        """
        获取任务详情
        :param task_id: 任务id
        :return:
        """
        mysql_conn = self.get_mysql_conn()
        task = dict()
        try:
            sql = ('SELECT task_id, title, content, originality_score, originality_details, status '
                   'FROM task '
                   'WHERE task_id = %s;')
            args = (task_id,)
            task = mysql_conn.fetchone(sql, args=args)
        finally:
            if "mysql_conn" in dir():  # 判断连接是否成功创建，创建了才能执行close()
                mysql_conn.close()

        return task

    def create_originality_check_task(self, content: str) -> int:
        """
        创建原创度检测任务
        :param content: 文章的正文
        :return:
        """
        mysql_conn = self.get_mysql_conn()
        task_id = None
        try:
            sql = ('INSERT INTO `task`(content) '
                   'VALUES(%s);')
            args = (content, )
            mysql_conn.execute(sql, args)
            # 提交事物
            mysql_conn.commit()

            # 查找自增id
            sql = 'SELECT LAST_INSERT_ID() AS task_id;'
            args = ()
            task_id = mysql_conn.fetchone(sql, args).get("task_id")
        except DatabaseError:
            mysql_conn.rollback()
            error_str = traceback.format_exc()
            logger.error(error_str)
        finally:
            if "mysql_conn" in dir():  # 判断连接是否成功创建，创建了才能执行close()
                mysql_conn.close()

        return task_id

    def update_originality(self, originality_score: float, originality_details: str, task_id: int):
        mysql_conn = self.get_mysql_conn()

        try:
            sql = ('UPDATE task SET originality_score = %s, originality_details = %s, status = %s '
                   'WHERE task_id = %s;')
            args = (originality_score, originality_details, TASK_STATUS["success"],
                    task_id)
            count = mysql_conn.execute(sql, args)
            mysql_conn.commit()
        except DatabaseError:
            mysql_conn.rollback()
            error_str = traceback.format_exc()
            logger.error(error_str)
        finally:
            if "mysql_conn" in dir():  # 判断连接是否成功创建，创建了才能执行close()
                mysql_conn.close()

    def update_task_status(self, status: int, task_id: int):
        mysql_conn = self.get_mysql_conn()

        try:
            sql = ('UPDATE task SET status = %s '
                   'WHERE task_id = %s;')
            args = (status,
                    task_id)
            count = mysql_conn.execute(sql, args)
            mysql_conn.commit()
        except DatabaseError:
            mysql_conn.rollback()
            error_str = traceback.format_exc()
            logger.error(error_str)
        finally:
            if "mysql_conn" in dir():  # 判断连接是否成功创建，创建了才能执行close()
                mysql_conn.close()


def main():
    task_dao = TaskDAO()
    content = """某某正文"""

    task_id = task_dao.create_originality_check_task(content=content)
    task_dao.update_originality(originality_score=34.55, originality_details=json.dumps([]), task_id=task_id)


if __name__ == '__main__':
    main()
